#coding=utf-8
import time
from django.shortcuts import render,redirect
from TestModel.models import *
import json

def register(request):
    if request.method=='GET':
        return render(request,'df_user/register.html')

    if request.method=='POST':
        post = request.POST
        uname = post.get('username')
        upwd = post.get('password')
        upwd2 = post.get('passwordagain')
        users = UserInfo.objects.filter(uname=uname)
        if len(users) == 1:
            context = {'title': '用户注册', 'error_name': '用户名已经存在 请重新输入', 'uname': uname, 'upwd': upwd}
            return render(request, 'df_user/register.html', context)
        else:
            # 判断两次密码
            if upwd != upwd2:
                return redirect('/user/register/')
            user = UserInfo()
            user.uname = uname
            user.upwd = upwd
            user.save()
            time.sleep(5)
            # 注册成功，转到登录页
            return redirect('/user/login')

def login(request):
    if request.method == 'GET':
        uname=request.COOKIES.get('uname','')
        context={'title':'用户登录','error_name':0,'error_pwd':0,'uname':uname}
        return render(request,'df_user/login.html',context)
    if request.method == 'POST':
        # 接受请求信息
        post = request.POST
        uname = post.get('username')
        upwd = post.get('password')
        # 根据用户名查询对象
        users = UserInfo.objects.filter(uname=uname)
        if len(users) == 1:
            if upwd == users[0].upwd:
                return redirect('/user/info/')
            else:
                context = {'title': '用户登录', 'error_name_pwd': '用户名密码错误 请重新输入', 'uname': uname, 'upwd': upwd}
                time.sleep(5)
                return render(request, 'df_user/login.html', context)
        else:
            context = {'title': '用户登录', 'error_name_pwd': '用户名密码错误 请重新输入', 'uname': uname, 'upwd': upwd}
            time.sleep(5)
            return render(request, 'df_user/login.html', context)

def info(request):
    if request.method == 'GET':
        return render(request, 'df_user/info.html')


def device_easy(request):
    if request.method == 'GET':
        return render(request, 'df_user/device_easy.html')


def device_kick(request):
     if request.method == 'GET':
        return render(request, 'df_user/device_kick.html')


def device_grasp(request):
    if request.method == 'GET':
        return render(request, 'df_user/device_grasp.html')

def device_legs_twitch(request):
    if request.method == 'GET':
        return render(request, 'df_user/device_legs_twitch.html')

def device_hands_twitch(request):
    if request.method == 'GET':
        return render(request, 'df_user/device_hands_twitch.html')

def device_head_move(request):
    if request.method == 'GET':
        return render(request, 'df_user/device_head_move.html')

def device_turn_over(request):
    if request.method == 'GET':
        return render(request, 'df_user/device_turn_over.html')

def device_hands_stretch(request):
    if request.method == 'GET':
        return render(request, 'df_user/device_hands_stretch.html')

def device_legs_stretch(request):
    if request.method == 'GET':
        return render(request, 'df_user/device_legs_stretch.html')

def fft_kick(request):
    if request.method == 'GET':
        return render(request, 'df_user/fft_kick.html')

def fft_grasp(request):
    if request.method == 'GET':
        return render(request, 'df_user/fft_grasp.html')

def fft_hands_twitch(request):
    if request.method == 'GET':
        return render(request, 'df_user/fft_hands_twitch.html')
def fft_head_move(request):
    if request.method == 'GET':
        return render(request, 'df_user/fft_head_move.html')

def fft_turn_over(request):
    if request.method == 'GET':
        return render(request, 'df_user/fft_turn_over.html')

def fft_hands_stretch(request):
    if request.method == 'GET':
        return render(request, 'df_user/fft_hands_stretch.html')

def fft_legs_stretch(request):
    if request.method == 'GET':
        return render(request, 'df_user/fft_legs_stretch.html')

def fft_legs_twitch(request):
    if request.method == 'GET':
        return render(request, 'df_user/fft_legs_twitch.html')

def draw_with_json(tag_url, volt_url, action, ndevices=3):
    tagData = []
    device_S = set()
    action_S = set()
    try:
        f_tag = open(tag_url, 'r')
        f_volt = open(volt_url, 'r')

        lines_tag = f_tag.readlines()   #返回列表,包含所有行
        lines_volt = f_volt.readlines()

        #The amount of voltage data is quite big, store them with a generator
        # volt_generater = (line for line in lines_volt)

        for line in lines_tag:                        #依次读取每行
            #Turn the str to dict for the convinience of index after
            json_line = json.loads(line)              #json数据转成字典

            #For future to cancel the parameter 'action'
            action_S.add(json_line['tag'])             #把tag存进action的集合

            #List tagData store the whole data of the certain action
            if json_line['tag'] == action:
                tagData.append(json_line)              #把筛选动作的那一行存进列表，列表里面包含字典

        # for line in lines_volt:
        #     json_line = json.loads(line)
        #     #For future to cancel the parameter 'ndevices'
        #     device_S.add(json_line['device_no'])

        ntags = len(tagData)                           #tag存了多少行
        n = 1

        fig = plt.figure(figsize=(6, 8))  #宽和高
        fig.suptitle(action)           #标题

        for data in tagData:
            initTime, termTime = data['inittime'], data["termtime"]
            print(initTime,termTime)

            times, volts = {}, {}                      #时间电压是字典，其中键值对中值就是列表，键就是设备号
            for i in range(1, ndevices + 1):
                times[i] = []
                volts[i] = []
            # I tried to use generator instead of list ,but I failed.
            # I don't know the exactly reason why generator can't work properly in a loop
            # for i in volt_generater:
            #     json_i = json.loads(i)
            #     if (json_i['time'] <= termTime) and (json_i['time'] >= initTime):
            #         device_no = int(json_i['device_no'])
            #         v = json_i['voltage']
            #         time = json_i['time']
            #         times[device_no].append(time)
            #         volts[device_no].append(v)

            for i in lines_volt:
                json_i = json.loads(i)
                device_S.add(json_i['device_no'])
                if (json_i['time'] <= termTime) and (json_i['time'] >= initTime):
                    device_no = int(json_i['device_no'])
                    v = json_i['voltage']
                    time = json_i['time']
                    times[device_no].append(time)
                    volts[device_no].append(v)
    finally:
        if f_tag:
            f_tag.close()
        if f_volt:
            f_volt.close()